package com.hongfeng.support.service.impl;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.hongfeng.support.item.QueryItem;
import com.hongfeng.support.item.tag.FieldOperator;
import com.hongfeng.support.model.Menu;
import com.hongfeng.support.model.Purview;
import com.hongfeng.support.model.Role;
import com.hongfeng.support.service.MenuService;
import com.hongfeng.support.service.PurviewService;
import com.hongfeng.support.service.RoleService;
import com.hongfeng.support.service.common.impl.GenericServiceImpl;
import com.hongfeng.support.util.json.JsonUtils;

@Service
public class PurviewServiceImpl extends GenericServiceImpl<Purview, Long>
		implements PurviewService {

	@Resource
	private RoleService roleService;
	@Resource
	private MenuService menuService;

	public PurviewServiceImpl() {
		super(Purview.class);
	}

	/**
	 * 创建权限数据
	 * 
	 * @param jsonObject
	 *            权限json数据
	 *            [{"id":"","role":{"id":"1"},"menu":{"id":"c_17,d_18,e_19"}}]
	 */
	public void create(String purviewJson) {
		JSONObject jsonObject = JsonUtils.json2Object(purviewJson);
		Object roleObj = jsonObject.get("role");
		Object menuObj = jsonObject.get("menu");
		if (roleObj == null || menuObj == null) {
			return;
		}
		JSONObject roleJsonObj = JsonUtils.json2Object(roleObj.toString());
		JSONObject menuJsonObj = JsonUtils.json2Object(menuObj.toString());
		Long roleId = roleJsonObj.getLong("id");
		Role role = roleService.read(roleId);
		String[] menuIdStrs = StringUtils.split(menuJsonObj.getString("id")
				.toString(), ",");
		for (String str : menuIdStrs) {
			String[] menuIdArr = StringUtils.split(str, "_");
			Long menuId = Long.valueOf(menuIdArr[menuIdArr.length - 1]);
			QueryItem item = new QueryItem(Purview.class);
			item.addCondition("role.id", FieldOperator.EQUAL, roleId);
			item.addCondition("menu.id", FieldOperator.EQUAL, menuId);
			List<Purview> purviews = super.findAll(item);
			if (purviews.size() == 0) {
				Menu menu = menuService.read(menuId);
				Purview purview = new Purview();
				purview.setRole(role);
				purview.setMenu(menu);
				super.create(purview);
			}
		}
	}

	/**
	 * 修改权限数据
	 */
	public void update(String purviewJson) {
		this.create(purviewJson);
	}

}
